//
//  GGScrollView.swift
//  AutoModel
//
//  Created by 好米有易 on 2019/9/6.
//  Copyright © 2019 own. All rights reserved.
//

import Cocoa
import Highlightr

class GGTextView: NSScrollView {

    private lazy var txtView: NSTextView = {
        let txtView = NSTextView()
        txtView.isEditable = true
        txtView.font = NSFont.systemFont(ofSize: 18)
        txtView.textColor = NSColor.purple
        txtView.textContainer?.size = NSMakeSize(1.0e7, 1.0e7)
        txtView.maxSize = NSMakeSize(1.0e7, 1.0e7)
        txtView.autoresizingMask = .none
        txtView.textContainer?.widthTracksTextView = false
        txtView.textContainer?.heightTracksTextView = false
        txtView.isHorizontallyResizable = true
        txtView.isVerticallyResizable = true
        return txtView;
    }()

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        self.borderType = NSBorderType.noBorder
        self.hasVerticalScroller = true
        txtView.frame = frameRect
        self.hasHorizontalScroller = true
        self.documentView = txtView
    }

    override func viewDidMoveToSuperview() {
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.new, context: nil)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let newFrame =  change?[NSKeyValueChangeKey.newKey] as? NSRect {
            txtView.frame = newFrame
        }
    }

    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension GGTextView {

    /// 设置文本
    ///
    /// - Parameter string: 文本字符串
    public func setText(string: String) {
        self.txtView.string = string
    }

    /// 设置代码高亮
    ///
    /// - Parameter string: 富文本字符串
    public func setCodeText(string: NSAttributedString) {
        self.txtView.insertText(string)
    }

    /// 设置背景主题色
    ///
    /// - Parameter color: 颜色
    public func setTheme(color: NSColor) {
        self.txtView.backgroundColor = color
    }

}
